import traceback

import openpyxl as openpyxl
from PyQt5.QtCore import QDate
from PyQt5.QtWidgets import QMessageBox, QFileDialog
from openpyxl.cell.text import Text

from base.base import BaseGui
from dao.rapid_bin_db import RapidBinManager
from enums.bin_enum import BinEnum
from rapid_api.bin import json_analysis_BIN
from utils.button_tablewidget import WithButtonTableWidget
from utils.excel import ExportExcelDialog


class MainGui(BaseGui):

    def __init__(self):
        super().__init__()

        self.page_size = 10  # 默认分页数
        self.page_num = 1  # 默认分页
        self.bin_headers = BinEnum.getDescList()
        self.binTableWidget = self.ui.binTableWidget
        self.page_data = None  # 当前页数据

        try:
            # 根据BIN 搜索
            self.ui.indexPushButton.clicked.connect(self.indexBIN)
            # 分页展示第一页
            self.show_page(page_num=self.page_num)
            # 下一页
            self.ui.page_down.clicked.connect(self.to_page_down)
            # 上一页
            self.ui.page_up.clicked.connect(self.to_page_up)
            # 导入excel 按钮
            self.ui.importExcel.clicked.connect(self.importBINs)
            # 导出 bin列表
            self.ui.exportBinPushButton.clicked.connect(self.exportBINs)
            # 监听 xx  ms
            self.ms.index_signal.connect(self.handle_results)

        except Exception as e:
            traceback.print_exc()
            QMessageBox.about(self.ui, "账号页点击错误", str(e))

    def show_page(self, page_num):
        self.binTableWidget.clear()
        self.page_data = None
        query_columns = BinEnum.getValuesStr()
        start = (page_num - 1) * self.page_size
        rapidBinManager = RapidBinManager()  #
        self.page_data = rapidBinManager.selectDataByPager(start, pageSize=self.page_size, query_columns=query_columns)
        WithButtonTableWidget(self, self.binTableWidget, self.page_data, self.bin_headers, 4)

    def to_page_down(self):
        self.page_num += 1
        self.show_page(self.page_num)

    def to_page_up(self):
        self.page_num -= 1
        if self.page_num == 0:
            self.page_num = 1
        self.show_page(self.page_num)

    def indexBIN(self):
        text = self.ui.indexLineEdit.text()
        if len(text) == 0:
            self.show_page(1)
            return
        if len(text) != 6:
            QMessageBox.about(self.ui, "error", f'请输入正确的BIN')
            return
        self.binTableWidget.clear()
        rapidBinManager = RapidBinManager()
        query_columns = BinEnum.getValuesStr()
        rapidBIN = rapidBinManager.selectInfoByBIN(text, query_columns)
        if rapidBIN is not None and len(rapidBIN) > 0:
            WithButtonTableWidget(self, self.binTableWidget, rapidBIN, self.bin_headers, 4)
        else:
            result = json_analysis_BIN(text)
            if result is not None:
                extracted_values = tuple(result.get(field, None) for field in BinEnum.getValuesList())
                WithButtonTableWidget(self, self.binTableWidget, [extracted_values], self.bin_headers, 4)
                rapidBinManager1 = RapidBinManager()
                rapidBinManager1.insertBindata(result)
            else:
                QMessageBox.about(self.ui, "error", f'当前BIN 查无数据')
                return

    def handle_results(self, result):
        pass

    def importBINs(self):
        QMessageBox.about(self.ui, "提示", "当前导入功能不开放！")
        return
        try:
            rapidBin = RapidBinManager()  # 代理信息 数据映射类
            fname, _ = QFileDialog.getOpenFileName(None, 'Open Excel File', '.', 'Excel files (*.xlsx)')
            if fname:
                wb = openpyxl.load_workbook(fname)
                sheet = wb.active
                rows = sheet.iter_rows(values_only=True)
                count = 0
                insert_rows = []
                for index, row in enumerate(rows):
                    count += 1
                    if row[0] is None:
                        continue
                    list_row = list(row)
                    for indx, ro in enumerate(list_row):
                        if indx > 28:
                            continue
                        if ro is None:
                            list_row[indx] = ''
                            continue
                        if isinstance(ro, Text):
                            list_row[indx] = ro.content
                        else:
                            list_row[indx] = str(ro)
                    new_row = tuple(list_row)
                    insert_rows.append(new_row)
                rapidBin.batchInsertBinByTuple(insert_rows, headers=self.bin_headers)
                QMessageBox.about(self.ui, "导入BIN信息任务", f'当前导入{len(insert_rows)}条 数据完成')
        except Exception as e:
            QMessageBox.about(self.ui, "当前导入报错", f'原因为：{e}')

    def exportBINs(self):
        rapid = RapidBinManager()
        start_time = QDate.currentDate().addDays(-3).toString("yyyy-MM-dd")  # 可拓展为页面选择
        end_time = QDate.currentDate().addDays(1).toString("yyyy-MM-dd")
        data = rapid.selectExportData(start_time, end_time)
        ExportExcelDialog(data)
        QMessageBox.about(self.ui, "导出BIN", f'导出数据：{len(data)} 条')
